<template>
  <div @click="barClick" ref="mpProgress" class="mpProgress">
    <div class="mpProgress-bar"></div>
    <div ref="mpPercentProgress" class="mpProgress-outer"></div>
    <div ref="mpProgressInner" class="mpProgress-inner">
      <div
        class="mpProgress-dot"
      ></div>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

const dotWidth = 10
export default {
  name: 'mp-progress',
  props: {
    percent: {
      type: Number,
      default: 0
    },
    percentProgress: {
      type: Number,
      default: 0
    }
  },
  watch: {
    percent(newPercent) {
      if(newPercent >= 0) {
        const barWidth = this.$refs.mpProgress.clientWidth - dotWidth
        const offsetWidth = newPercent * barWidth
        this.moveSlide(offsetWidth)
      }
    },
    percentProgress(newPercent) {
      if(newPercent >= 0) {
        const offsetWidth = newPercent * (this.$refs.mpProgress.clientWidth - dotWidth)
        this.moveBuffered(offsetWidth)
      }
    }
  },
  methods: {
    moveSlide(offsetWidth) {
      this.$refs.mpProgressInner.style.width = offsetWidth + 'px'
    },
    moveBuffered(offsetWidth) {
      this.$refs.mpPercentProgress.style.width = offsetWidth + 'px'
    },
    barClick(e) {
      const barWidth = this.$refs.mpProgress.offsetWidth
      const offsetWidth = e.offsetX - dotWidth / 2
      this.moveSlide(offsetWidth)
      this.changeCurrentTime(offsetWidth / barWidth)
    },
    ...mapActions(['changeCurrentTime'])
  }
}
</script>

<style lang="scss" scoped>
  .mpProgress {
    position: relative;
    padding: 5px;
    user-select: none;
    cursor: pointer;
    overflow: hidden;
    .mpProgress-bar {
      height: 2px;
      width: 100%;
      background: $bar_color;
    }
    .mpProgress-outer {
      position: absolute;
      top: 50%;
      left: 5px;
      display: inline-block;
      width: 0;
      height: 2px;
      margin-top: -1px;
      background: rgba(255, 255, 255, 0.2);
    }
    .mpProgress-inner {
      position: absolute;
      top: 50%;
      left: 5px;
      display: inline-block;
      width: 0;
      height: 2px;
      margin-top: -1px;
      background: $line_color;
      .mpProgress-dot {
        position: absolute;
        top: 50%;
        right: -5px;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: $dot_color;
        transform: translateY(-50%);
      }
    }
  }
</style>